import { routesMap, commonRoutes } from '@/router'

const permission = {
	state: {
		routers: commonRoutes,
		addRouters: [],
		roleList: [] // 用户权限
	},
	mutations: {
		SET_ROUTERS: (state, routers) => {
			state.addRouters = routers
			state.routers = commonRoutes.concat(routers)
		},
		SET_ROLELIST: (state, roles) => {
			state.roleList = roles
		}
	},
	actions: {
		GenerateRoutes({ commit }, data) {
			return new Promise(resolve => {
				const { roles } = data
				let accessedRouters
				for (var key = 0; key < routesMap.length; key++) {
					// 如果一级菜单需要权限访问
					if (routesMap[key]['roles']) {
						// 首先判断一级菜单是否包含此权限
						let has = false
						key = parseInt(key) // 转数字
						/* for (const i of routesMap[key]['roles']) {
							if (roles['list'].indexOf(i) >= 0) {
								has = true
							}
						} */
						if (roles['list'].indexOf(routesMap[key]['roles']) >= 0) {
							has = true
						}
						// 如果不存在则移出权限列表
						if (!has) {
							routesMap.splice(key, 1)
							key = key - 1
						}
					}
				}
				accessedRouters = routesMap
				// accessedRouters = filterAsyncRouter(asyncRouterMap, roles)
				commit('SET_ROLELIST', roles['list'])
				commit('SET_ROUTERS', accessedRouters)
				resolve()
			})
		}
	}
}

export default permission
